// 自动为所有页面应用全局加载效果的脚本
const fs = require('fs')
const path = require('path')

// 页面路径映射
const pagePaths = [
  'pages/service/civil-affairs/apply',
  'pages/common/search-results',
  'pages/common/index',
  'pages/admin/cases',
  'pages/service/index',
  'pages/service/comprehensive-governance/dispute-mediation',
  'pages/user/mine',
  'pages/user/favorites',
  'pages/user/progress',
  'pages/auth/forgot-password',
  'pages/auth/login',
  'pages/auth/bind-email',
  'pages/auth/register',
  'pages/user/mine/profile',
  'pages/activity/detail',
  'pages/admin/activities',
  'pages/user/activities',
  'pages/admin/notices',
  'pages/user/progress/detail',
  'pages/admin/cases/detail',
  'pages/admin/users',
  'pages/admin/index',
  'pages/admin/chart-analysis',
  'pages/admin/stats',
  'pages/village/notice-detail',
  'pages/service/civil-affairs/pension-subsidy',
  'pages/service/public-services/streetlight-repair',
  'pages/village/complaints',
  'pages/admin/feedback',
  'pages/service/certificate-services/resident-proof',
  'pages/service/comprehensive-governance/security-incident-report',
  'pages/service/agriculture-rural/machinery-subsidy',
  'pages/service/urban-rural-construction/homestead-apply',
  'pages/service/civil-affairs/relief',
  'pages/village/open',
  'pages/common/about',
  'pages/village/cases'
]

// 页面类型对应的加载文本
const loadingTextMap = {
  'service': '服务事项加载中...',
  'user': '用户信息加载中...',
  'admin': '管理数据加载中...',
  'village': '村务信息加载中...',
  'auth': '身份验证中...',
  'activity': '活动信息加载中...',
  'common': '页面加载中...'
}

// 获取页面类型
function getPageType(pagePath) {
  if (pagePath.includes('/service/')) return 'service'
  if (pagePath.includes('/user/')) return 'user'
  if (pagePath.includes('/admin/')) return 'admin'
  if (pagePath.includes('/village/')) return 'village'
  if (pagePath.includes('/auth/')) return 'auth'
  if (pagePath.includes('/activity/')) return 'activity'
  return 'common'
}

// 更新页面的JSON配置文件
function updatePageJson(pagePath) {
  const jsonPath = path.join(__dirname, '..', pagePath, 'index.json')
  
  if (!fs.existsSync(jsonPath)) {
    console.log(`跳过不存在的JSON文件: ${jsonPath}`)
    return
  }

  try {
    const jsonContent = fs.readFileSync(jsonPath, 'utf8')
    const jsonConfig = JSON.parse(jsonContent)
    
    // 添加全局加载组件
    if (!jsonConfig.usingComponents) {
      jsonConfig.usingComponents = {}
    }
    
    jsonConfig.usingComponents['global-loading'] = '/components/global-loading/global-loading'
    
    fs.writeFileSync(jsonPath, JSON.stringify(jsonConfig, null, 2))
    console.log(`✓ 更新JSON配置: ${pagePath}`)
  } catch (error) {
    console.error(`✗ 更新JSON配置失败: ${pagePath}`, error.message)
  }
}

// 更新页面的WXML文件
function updatePageWxml(pagePath) {
  const wxmlPath = path.join(__dirname, '..', pagePath, 'index.wxml')
  
  if (!fs.existsSync(wxmlPath)) {
    console.log(`跳过不存在的WXML文件: ${wxmlPath}`)
    return
  }

  try {
    let wxmlContent = fs.readFileSync(wxmlPath, 'utf8')
    
    // 检查是否已经包含全局加载组件
    if (wxmlContent.includes('<global-loading')) {
      console.log(`✓ 已包含全局加载组件: ${pagePath}`)
      return
    }
    
    // 在页面末尾添加全局加载组件
    const globalLoadingTag = '\n<!-- 全局加载组件 -->\n<global-loading \n  global-loading="{{globalLoading}}" \n  global-loading-text="{{globalLoadingText}}">\n</global-loading>\n'
    
    // 查找最后一个</view>标签并在此之前插入
    const lastViewIndex = wxmlContent.lastIndexOf('</view>')
    if (lastViewIndex !== -1) {
      wxmlContent = wxmlContent.slice(0, lastViewIndex) + globalLoadingTag + wxmlContent.slice(lastViewIndex)
    } else {
      // 如果没有找到</view>，直接添加到末尾
      wxmlContent += globalLoadingTag
    }
    
    fs.writeFileSync(wxmlPath, wxmlContent)
    console.log(`✓ 更新WXML模板: ${pagePath}`)
  } catch (error) {
    console.error(`✗ 更新WXML模板失败: ${pagePath}`, error.message)
  }
}

// 更新页面的JS文件
function updatePageJs(pagePath) {
  const jsPath = path.join(__dirname, '..', pagePath, 'index.js')
  
  if (!fs.existsSync(jsPath)) {
    console.log(`跳过不存在的JS文件: ${jsPath}`)
    return
  }

  try {
    let jsContent = fs.readFileSync(jsPath, 'utf8')
    
    // 检查是否已经包含全局加载相关代码
    if (jsContent.includes('globalLoading') || jsContent.includes('showGlobalLoading')) {
      console.log(`✓ 已包含全局加载代码: ${pagePath}`)
      return
    }
    
    const pageType = getPageType(pagePath)
    const loadingText = loadingTextMap[pageType] || '页面加载中...'
    
    // 添加全局加载相关的数据和方法
    const loadingCode = `
  // 全局加载状态
  globalLoading: false,
  globalLoadingText: '${loadingText}',

  // 显示全局加载
  showGlobalLoading(text = '${loadingText}') {
    const app = getApp()
    app.showGlobalLoading({
      loadingText: text
    })
  },

  // 隐藏全局加载
  hideGlobalLoading() {
    const app = getApp()
    app.hideGlobalLoading()
  },

  // 更新全局加载状态
  updateGlobalLoading(data) {
    this.setData({
      globalLoading: data.globalLoading,
      globalLoadingText: data.globalLoadingText || this.data.globalLoadingText
    })
  },`
    
    // 在data对象中添加全局加载状态
    const dataIndex = jsContent.indexOf('data: {')
    if (dataIndex !== -1) {
      const dataEndIndex = jsContent.indexOf('}', dataIndex) + 1
      jsContent = jsContent.slice(0, dataEndIndex) + ',' + loadingCode + jsContent.slice(dataEndIndex)
    }
    
    // 在onLoad方法中添加页面加载效果
    if (jsContent.includes('onLoad(options)')) {
      const onLoadStart = jsContent.indexOf('onLoad(options)')
      const onLoadEnd = jsContent.indexOf('}', onLoadStart) + 1
      const onLoadContent = jsContent.slice(onLoadStart, onLoadEnd)
      
      if (!onLoadContent.includes('showGlobalLoading')) {
        const newOnLoadContent = onLoadContent.replace(
          'onLoad(options) {',
          `onLoad(options) {
    // 显示页面加载效果
    this.showGlobalLoading('${loadingText}')`
        )
        
        jsContent = jsContent.replace(onLoadContent, newOnLoadContent)
      }
    }
    
    // 在onReady方法中添加隐藏加载效果
    if (jsContent.includes('onReady()')) {
      const onReadyStart = jsContent.indexOf('onReady()')
      const onReadyEnd = jsContent.indexOf('}', onReadyStart) + 1
      const onReadyContent = jsContent.slice(onReadyStart, onReadyEnd)
      
      if (!onReadyContent.includes('hideGlobalLoading')) {
        const newOnReadyContent = onReadyContent.replace(
          'onReady() {',
          `onReady() {
    // 页面准备完成，隐藏加载效果
    setTimeout(() => {
      this.hideGlobalLoading()
    }, 500)`
        )
        
        jsContent = jsContent.replace(onReadyContent, newOnReadyContent)
      }
    }
    
    fs.writeFileSync(jsPath, jsContent)
    console.log(`✓ 更新JS逻辑: ${pagePath}`)
  } catch (error) {
    console.error(`✗ 更新JS逻辑失败: ${pagePath}`, error.message)
  }
}

// 主函数
function main() {
  console.log('开始为所有页面应用全局加载效果...\n')
  
  let successCount = 0
  let totalCount = pagePaths.length
  
  pagePaths.forEach((pagePath, index) => {
    console.log(`[${index + 1}/${totalCount}] 处理页面: ${pagePath}`)
    
    try {
      updatePageJson(pagePath)
      updatePageWxml(pagePath)
      updatePageJs(pagePath)
      successCount++
      console.log(`✓ 完成: ${pagePath}\n`)
    } catch (error) {
      console.error(`✗ 失败: ${pagePath}`, error.message, '\n')
    }
  })
  
  console.log(`\n处理完成! 成功: ${successCount}/${totalCount}`)
  console.log('\n注意事项:')
  console.log('1. 请检查所有页面的加载效果是否正常工作')
  console.log('2. 如有需要，可以手动调整各页面的加载文本')
  console.log('3. 建议在页面数据加载完成后调用hideGlobalLoading()方法')
}

// 运行脚本
if (require.main === module) {
  main()
}

module.exports = {
  updatePageJson,
  updatePageWxml,
  updatePageJs,
  pagePaths,
  loadingTextMap
}
